import {
  Button, Card, Col, Form, Input, message, Row,
} from 'antd'
import {
  FC, useReducer, useState, useCallback, useRef, useEffect,
} from 'react'
import styled from 'styled-components'
import { postCheckPhoneApi, postPhoneCodeApi, postRegisterApi } from '@/api/auth'

const bj = require('../../assets/bj.png')

const RegisterStyle = styled.div`
  height: 100%;
  background-image: url(${bj});
  position: relative;
  .register-card {
  padding: 30px;
  height: 480px;
  width: 420px;
  position: absolute;
  right: 100px;
  top: 70px;
}
`
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
}

const reducer = (state: { tel: string}, action: { type: string, payload: string | undefined }) => {
  const newState = { ...state }
  if (action.type === 'updatePhone') newState.tel = action.payload!
  return newState
}

const AppRegister: FC = (props:any) => {
  const [state, dispatch] = useReducer(reducer, { tel: '' })
  const [telCode, setTelCode] = useState('')
  const [time, setTime] = useState(10)
  const { history } = props
  const timer = useRef<null | NodeJS.Timer>(null)
  const [form] = Form.useForm()

  const handleSendCode = useCallback(() => {
    setTime(10)
    clearInterval(timer.current!)
    timer.current = null
    timer.current = setInterval(() => {
      setTime((t) => (t - 1))
    }, 500)
    // 调用接口
    postPhoneCodeApi(state.tel).then((code) => setTelCode(String(code.data)))
  }, [time])
  useEffect(() => {
    if (time === 0) {
      clearInterval(timer.current!)
      setTime(10)
    }
  }, [time])

  const onFinish = useCallback(async (values:any) => {
    const { tel, telcode } = values
    try {
      await postCheckPhoneApi(tel)
      dispatch({ type: 'updatePhone', payload: tel })
    } catch (error) {
      console.log(error)
    }
    console.log(telCode)
    if (telcode && telcode === telCode) {
      postRegisterApi(tel, telcode)
      history.push('/login')
    } else {
      message.error('请输入正确的验证码')
    }
  }, [telCode])
  return (
    <RegisterStyle>
      <Card className="register-card" title="注册用户" bordered={false}>
        <Form
          {...formItemLayout}
          form={form}
          name="register"
          onFinish={onFinish}
          scrollToFirstError
        >
          <Form.Item
            name="tel"
            label="手机号"
            rules={[
              {
                required: true,
                message: '请输入你的手机号!',
              },
              {
                len: 11,
              },
            ]}
          >
            <Input placeholder="Telephone Number" />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              {
                required: true,
                message: '请输入你的密码!',
              },
              {
                max: 12,
                min: 6,
              },
            ]}
            hasFeedback
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="confirm"
            label="确认密码"
            dependencies={['password']}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请再次输入密码!',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            label="用户名"
            name="adminname"
            rules={[
              {
                required: true,
                message: '请输入你的昵称!',
                whitespace: true,
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="验证码">
            <Row gutter={8}>
              <Col span={12}>
                <Form.Item
                  name="telcode"
                  noStyle
                  rules={[
                    {
                      required: true,
                      message: '请输入你的验证码!',
                    },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Button disabled={ time > 0 && time !== 10 } onClick={ handleSendCode }>
                  获取验证码
                  { time }
                  s
                </Button>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              注册
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </RegisterStyle>
  )
}

export default AppRegister
